package cn.huiyunche.base.service.interfaces.impl;

import cn.huiyunche.base.service.interfaces.BAreaService;
import cn.huiyunche.base.service.interfaces.SUserRouteService;
import cn.huiyunche.base.service.mappers.SUserRouteMapper;
import cn.huiyunche.base.service.mappers.ext.SUserRouteViewMapper;
import cn.huiyunche.base.service.model.BArea;
import cn.huiyunche.base.service.model.SUserRoute;
import cn.huiyunche.base.service.model.SUserRouteExample;
import cn.huiyunche.base.service.vo.PageVo;
import cn.huiyunche.base.service.vo.Result;
import cn.huiyunche.base.service.vo.SUserRouteVo;
import cn.huiyunche.tools.basic.exceptions.BusinessException;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @FileName: cn.huiyunche.service.base.interfaces.impl
 * @Description: Description
 * @author: Aaron
 * @date: 2016/12/10 上午11:50
 */
@Service
public class SUserRouteServiceImpl implements SUserRouteService {

    private static final Logger LOGGER = LoggerFactory.getLogger(SUserRouteServiceImpl.class);

    @Autowired
    private SUserRouteMapper sUserRouteMapper = null;

    @Autowired
    private SUserRouteViewMapper sUserRouteViewMapper = null;

    @Autowired
    private BAreaService bAreaService = null;

    private BAreaService getBAreaService() {
        return this.bAreaService;
    }

    private SUserRouteViewMapper getSUserRouteViewMapper() {
        return this.sUserRouteViewMapper;
    }

    private SUserRouteMapper getSUserRouteMapper() {
        return this.sUserRouteMapper;
    }

    @Override
    public List<SUserRoute> getListByUserId(Long userId) {
        LOGGER.info("getListByUserId param : {}", userId);
        if (null == userId) {
            LOGGER.error("getListByUserId param userId must not be null");
            throw new IllegalArgumentException("户主键不能为空");
        }

        SUserRouteExample example = new SUserRouteExample();
        example.createCriteria().andUserIdEqualTo(userId);

        List<SUserRoute> list = sUserRouteMapper.selectByExample(example);
        if (CollectionUtils.isNotEmpty(list)) {
            return list;
        }

        return null;
    }

    @Override
    public Result<Object> modifyRouter(SUserRouteVo routeVo) throws Exception {
        LOGGER.info("modifyRouter params routeVo: {}", routeVo);
        Result<Object> result = new Result<>(true, null, "数据操作已成功");
        SUserRoute record = new SUserRoute();
        try {
            PropertyUtils.copyProperties(record, routeVo);
        } catch (Exception e) {
            LOGGER.error("copy routeVo error: {}", e);
            throw new BusinessException("对象转换异常");
        }
        List<BArea> orgin = this.getBAreaService().selectAreaByCode(routeVo.getOrginCode());
        if (CollectionUtils.isNotEmpty(orgin)) {
            record.setOrginName(orgin.get(0).getName());
        }
        List<BArea> dest = this.getBAreaService().selectAreaByCode(routeVo.getDestCode());
        if (CollectionUtils.isNotEmpty(orgin)) {
            record.setDestName(dest.get(0).getName());
        }
        // 校验信息
        this.checkRoute(record);
        if (null == routeVo.getId()) {
            result.setData(this.getSUserRouteMapper().insertSelective(record));
        } else {
            result.setData(this.getSUserRouteMapper().updateByPrimaryKeySelective(record));
        }
        return result;
    }

    @Override
    public Result<Object> delRouter(Long id) throws Exception {
        LOGGER.info("delRouter params id: {}", id);
        if (null == id || id == 0) {
            LOGGER.info("id is null");
            throw new BusinessException("线路ID不能为空");
        }
        Result<Object> result = new Result<>(true, null, "删除线路成功");
        result.setData(this.getSUserRouteMapper().deleteByPrimaryKey(id));
        return result;
    }

    @Override
    public Result<Map<String, Object>> list(PageVo pageVo, SUserRouteVo routeVo) throws Exception {
        LOGGER.info("list params pageVo: {}, routeVo: {}", pageVo, routeVo);
        Result<Map<String, Object>> result = new Result<>(true, null, "数据加载成功");
        Map<String, Object> map = new HashMap<>();
        pageVo.setTotalRecord(this.getSUserRouteViewMapper().countByExample(routeVo.getUserId(), routeVo.getOrginCode(), routeVo.getDestCode()));
        List<SUserRouteVo> lists = this.getSUserRouteViewMapper().selectByExample(pageVo, routeVo.getUserId(), routeVo.getOrginCode(), routeVo.getDestCode());
        map.put("route", lists);
        map.put("page", pageVo);
        result.setData(map);
        return result;
    }

    @Override
    public Result<Object> getById(Long id) throws Exception {
        LOGGER.info("getById params id: {}", id);
        if (null == id || id == 0) {
            LOGGER.info("id is null");
            throw new BusinessException("线路ID不能为空");
        }
        Result<Object> result = new Result<>(true, null, "数据加载成功");
        result.setData(this.getSUserRouteMapper().selectByPrimaryKey(id));
        return result;
    }

    @Override
    public SUserRoute selectByPrimary(Long routeId) {
        LOGGER.info("selectByPrimary param : {}", routeId);
        if (null == routeId) {
            LOGGER.error("selectByPrimary param routeId must not be null");
            throw new IllegalArgumentException("线路主键不能为空");
        }

        return sUserRouteMapper.selectByPrimaryKey(routeId);
    }

    private void checkRoute(SUserRoute route) throws Exception {
        if (StringUtils.isBlank(route.getDestCode())) {
            LOGGER.info("destCode is null");
            throw new BusinessException("目的地编码不能为空");
        } else if (StringUtils.isBlank(route.getOrginCode())) {
            LOGGER.info("orgincode is null");
            throw new BusinessException("起始地编码不能为空");
        } else if (null == route.getUserId()) {
            LOGGER.info("userid is null");
            throw new BusinessException("用户ID不能为空");
        } else if (StringUtils.isBlank(route.getDestName())) {
            LOGGER.info("destName is null");
            throw new BusinessException("目的地名称不能为空");
        } else if (StringUtils.isBlank(route.getOrginName())) {
            LOGGER.info("orginName is null");
            throw new BusinessException("起始地名称不能为空");
        } else if (route.getMaximumEveryDay() == 0) {
            LOGGER.info("maximumEveryDay is null");
            throw new BusinessException("每天申请的最大运单数不能为0");
        } else if (route.getMaximumEveryDay() > 30) {
            LOGGER.info("The input value is too large");
            throw new BusinessException("每天申请的最大运单数不能大于30");
        }
        List<SUserRoute> lists = new ArrayList<>();
        if (null != route.getId() && route.getId() != 0) {
            SUserRouteExample example = new SUserRouteExample();
            example.createCriteria().andOrginCodeEqualTo(route.getOrginCode()).andDestCodeEqualTo(route.getDestCode()).andIdNotEqualTo(route.getId()).andUserIdEqualTo(route.getUserId());
            lists = this.getSUserRouteMapper().selectByExample(example);
        } else {
            SUserRouteExample example = new SUserRouteExample();
            example.createCriteria().andOrginCodeEqualTo(route.getOrginCode()).andDestCodeEqualTo(route.getDestCode()).andUserIdEqualTo(route.getUserId());
            lists = this.getSUserRouteMapper().selectByExample(example);
        }
        if (CollectionUtils.isNotEmpty(lists)) {
            LOGGER.info("current line is exit");
            throw new BusinessException("当前线路已存在");
        }
    }
}
